#include "longpoll_api.h"
#include "longpoll_sdk.h"

LongPoll* CreateLongPollEnv(int longpoll_timeout, char* p_servers, ConstructLongPollDUPReqFn ConstructLongPollDUPReq, OnNotifyFn OnNotify, AfterNotifyCB pCallback, void* arg, void* reserve)
{
	LongPoll* p_longpoll_env = NULL;
	try
	{
		p_longpoll_env = new LongPoll( longpoll_timeout, p_servers, ConstructLongPollDUPReq, OnNotify, pCallback, arg, reserve);
	}
        catch (std::exception e)
        {
                LONGPOLLALERTERRORLOG("CreateLongPollEnv failed:[%s]", -1, "", e.what());
                return NULL;
        }
	return p_longpoll_env;
}

int StartLongPoll(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->StartLongPollAsync();
}

void DestroyLongPollEnv(LongPoll* p_longpoll_env)
{
	try
	{
		if(p_longpoll_env != NULL)
		{
			delete p_longpoll_env;
		}
		p_longpoll_env = NULL;
	}
	catch (std::exception e)
	{
		LONGPOLLALERTERRORLOG("DestoryLongPollEnv fail:[%s]", -1, "", e.what());
	}
}

void* GetLongPollReserve(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->reserve;
}

const char* GetLongPollClientId(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->client_id.c_str();
}

const char* GetLongPollClientIp(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->client_ip.c_str();
}

int GetLongPollClientPort(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->client_port;
}

const char* GetLongPollServerIp(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->p_current_host->ip;
}

int GetLongPollServerPort(LongPoll* p_longpoll_env)
{
	return p_longpoll_env->p_current_host->port;
}

void SetLongPollRebalanceFlag(LongPoll* p_longpoll_env, bool flag)
{
	p_longpoll_env->g_rebalance_flag = flag;
	return;
}

int InitLongPollLogEnv()
{
	return InitLogEnv();
}

void CleanLongPollLogEnv()
{
	CleanLogEnv();
	return;
}

void SetLongPollLoglevel( char* p_loglevel )
{
	SetLoglevel( p_loglevel );
	return;
}

int LongPollWriteAlertLog( char *c_filename , long c_fileline , int log_level, char *format , ... )
{
	va_list		valist;
	char		buffer[1024];
	int		nret ;

	memset(buffer, 0x00, sizeof(buffer));
	va_start( valist , format );
	vsnprintf( buffer, sizeof(buffer), format, valist );
	va_end( valist );
	nret = WriteAlertLog( c_filename, c_fileline, log_level, "%s", buffer );
	return nret;
}

